package utils

import (
	message "chat/common"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"net"
)

type Transfer struct {
	Conn net.Conn
	Buf  [8096]byte
}

func (that *Transfer) ReadPkg() (mes message.Message, err error) {
	length, err := that.Conn.Read(that.Buf[:4])
	if length != 4 || err != nil {
		return
	}
	pkgLen := binary.BigEndian.Uint32(that.Buf[:4])
	_, err = that.Conn.Read(that.Buf[:pkgLen])
	if err != nil {
		return
	}
	err = json.Unmarshal(that.Buf[:pkgLen], &mes)
	if err != nil {
		return
	}
	return
}

func (that *Transfer) WritePkg(data []byte) (err error) {
	resultPkg := uint32(len(data))
	binary.BigEndian.PutUint32(that.Buf[:4], resultPkg)
	n, err := that.Conn.Write(that.Buf[:4])
	if n != 4 || err != nil {
		fmt.Println("WritePkg长度发送失败，err=", err)
		return
	}
	n, err = that.Conn.Write(data)
	if n != int(resultPkg) || err != nil {
		fmt.Println("WritePkg内容发送失败，err=", err)
		return
	}
	return
}
